//
//  YTFRefreshView.swift
//  sinaWeibo
//
//  Created by pro on 16/3/5.
//  Copyright © 2016年 pro. All rights reserved.
//

import UIKit
import SnapKit


//视图存在三个状态
enum RefreshType: Int {
    //正常状态
    case Normal = 0
    //拖拽状态
    case Pulling = 1
    //加载状态
    case Loading = 2
}

class YTFRefreshView: UIControl {

    //定义一个成员变量
    var scrollView: UIScrollView?
    
    //记录一下过去的状态
    var oldStatus: RefreshType = .Normal
    
    //定义一个属性，来记录状态，默认是正常状态
    var status:RefreshType = .Normal {
        
        didSet{
            
            switch status{
                
            case.Normal: print("正常状态")
                
                messageLabel.text = "下拉刷新"
                loadingImageView.hidden = true
                arrowImageView.hidden = false
                
            case.Pulling: print("下拉状态")
                
                messageLabel.text = "释放刷新"
                loadingImageView.hidden = true
                arrowImageView.hidden = false
                
            case.Loading: print("加载中...")
                
                messageLabel.text = "加载中..."
                loadingImageView.hidden = false
                arrowImageView.hidden = true
                
                //加载的时候，让视图显示在NAV的下面，修改scrollView?.contentInset
                var inset = scrollView?.contentInset
                
                inset?.top += 64
                
                scrollView?.contentInset = inset!
            
                //没有触发valueChange的事件
                sendActionsForControlEvents(UIControlEvents.ValueChanged)
                
                //记录加载的状态
                oldStatus = .Loading
                
            }
            
        }
    
    }
    
    //加载完成
    func endRefreshing(){
        
        //加载完成
        status = .Normal
        
        if oldStatus == .Loading {
            
            //加载的时候，让视图显示在NAV的里面，修改scrollView?.contentInset
            var inset = scrollView?.contentInset
            inset?.top -= 64
            scrollView?.contentInset = inset!
            
            //恢复标记
            oldStatus = .Normal
        }
        
    
    }
    
    //自定控件三步骤
    //重写构造方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        backgroundColor = UIColor(white: 230/225.0, alpha: 1.0)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //定义一个私有方法，添加视图并设置约束
    private func setupUI(){
        
        //设置frame
        //获取系统的frame
        var frame = self.frame
        //修改frame
        frame.size = CGSizeMake(kUIScreenWidth, 50)
        frame.origin.y = -50
        //赋值
        self.frame = frame
        
        
        //添加视图
        addSubview(messageLabel)
        addSubview(arrowImageView)
        addSubview(loadingImageView)
        
        //添加约束
        //提示语
        messageLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX).offset(30)
            make.centerY.equalTo(self.snp_centerY)
        }
        
        //箭头
        arrowImageView.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(self.snp_centerY)
            make.right.equalTo(messageLabel.snp_left)
        }
        
        //加载
        loadingImageView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowImageView.snp_center)
        }
        
    }
    
    //添加KVO
    //这个方法是，我们把子控件添加到父控件的时候回调用
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        
        //1.先把newSuperview转换为UIScrollView
        scrollView = newSuperview as? UIScrollView
        
        //2.添加监听
        scrollView?.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
    }
    
    //实现监听的KVO方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        let scrollView = object as? UIScrollView
        
        //给scrollView一个强转，不建议直接强转
        if scrollView!.dragging{//拖拽的时候，再去判断状态
            
            if scrollView?.contentOffset.y < -150 {
                //改变状态
                status = .Pulling
                
                //调用方法，改变视图
                
            }else if scrollView?.contentOffset.y < -114 && scrollView?.contentOffset.y > -150 {
                //修改状态
                status = .Normal
                
                //调用方法，改变视图
            }
            
        }else{//松手的状态
            //当scrollView?.contentOffset.y在一定范围内，去加载
            if scrollView?.contentOffset.y < -150 && status == .Pulling{
                status = .Loading
                
                //加载数据
            }
        
        }
    }
    
    
    //懒加载
    //提示语
    private lazy var messageLabel: UILabel = {
        
        let label = UILabel()
        
        label.text = "下拉刷新"
        
        label.textColor = UIColor.orangeColor()
        
        label.font = UIFont.systemFontOfSize(15)
        
        return label
    }()
    
    
    //箭头
    private lazy var arrowImageView:UIImageView = {
        
        let img = UIImageView()
        
        img.image = UIImage(named: "tableview_pull_refresh")
        
        return img
    }()
    
    //加载的视图
    private lazy var loadingImageView: UIImageView = {
        
        let img = UIImageView()
        
        img.image = UIImage(named: "tableview_loading")
        
        img.hidden = true
        
        return img
    }()
    
    
}










